<template>
  <div class="input-header">
    <!-- <div v-if="placeholder" class="placeholder">@ {{ placeholder }}</div> -->
    <div
      ref="inputCommentRef"
      contenteditable="true"
      class="comment-content input-inputText"
      :style="{ '--size': props.parent ? '1.2rem' : '1rem' }"
      :rows="3"
      :cols="20"
      @input="inputComment"
      @focus="focusComment"
      @blur="blurComment"
      @click="blurComment"
      :placeholder="placeholder"
    ></div>
    <div class="comment-picture" v-if="!props.multiplyImage && toWindowUrl">
      <img width="64" height="64" :src="toWindowUrl" />
      <div @click="removePicture">
        <span>X</span>
      </div>
    </div>
  </div>
  <div class="image-list" v-if="props.multiplyImage && images.length">
    <div
      v-for="(image, index) in images"
      :key="image.id"
      class="image-container"
    >
      <img :src="image.url" alt="" />
      <el-icon @click="deleteMulPic(index)" size="1.5rem" color="red"
        ><Delete
      /></el-icon>
    </div>
  </div>
  <div class="icon-input">
    <div class="icon-select">
      <IconList @select-icon="selectIcon" />
      <div class="input-picture" @click="inputPicture">
        <el-icon><PictureFilled /></el-icon>
      </div>
    </div>
    <div style="margin-right: 5px">
      <el-button
        type="danger"
        :disabled="!props.inputText"
        class="clear-btn"
        @click="clear"
        >清空</el-button
      >
      <el-button
        type="primary"
        :disabled="!props.inputText"
        class="publish-btn"
        @click="publish"
        >发送</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { debounce } from "@/utils/tools";
import IconList from "./Icons.vue";
import { ElNotification } from "element-plus";

interface ImageType {
  id: string;
  url: string;
}
const emit = defineEmits(["update:inputText", "publish"]);

const props = defineProps({
  inputText: {
    type: String,
    default: "",
  },
  showPublishButton: {
    type: Boolean,
    default: false,
  },
  placeholder: {
    type: String,
    default: "",
  },
  parent: {
    type: Boolean,
    default: false,
  },
  multiplyImage: {
    type: Boolean,
    default: false,
  },
});
const getCurrentIndex = () => {
  var range: any;
  if (window.getSelection) {
    //ie11 10 9 ff safari
    range = window.getSelection(); //创建range
    return range.focusOffset;
  } else if ((document as any).selection) {
    range = (document as any).selection.createRange(); //创建选择对象
    return range.focusOffset;
  }
};
const inputCommentRef = ref();
const showPublish = ref(false);
const currentIndex = ref(0);
const fileList = ref<any>([]);
const images = ref<ImageType[]>([]);
const previewList = ref<string[]>([]);
const toWindowUrl = ref("");
// 传值

function updateText() {
  emit("update:inputText", {
    text: inputCommentRef.value.innerHTML,
    parent: props.parent,
  });
}

const inputComment = debounce(updateText, 100);
// 鼠标聚焦
const focusComment = () => {
  showPublish.value = true;
};

const blurComment = () => {
  currentIndex.value = getCurrentIndex();
  // showPublish.value = false;
};

const deleteMulPic = (index: number) => {
  images.value.splice(index, 1);
};

const inputPicture = () => {
  let inputFile: any = document.createElement("input");
  inputFile.type = "file";
  inputFile.accept = "image/*";
  inputFile.multiple = props.multiplyImage;
  const windowURL = window.URL || window.webkitURL; // 兼容操作
  // const max = props.maxNumber - 1
  inputFile.onchange = () => {
    if (props.multiplyImage) {
      const files: FileList = inputFile?.files || null;
      Array.from(files).forEach((file: File) => {
        if (file.size < 2480000) {
          const url = windowURL.createObjectURL(file);
          if (images.value.length > 8) {
            return ElNotification.warning({
              title: "Warning",
              message: "只能选择9张图片",
              offset: 100,
            });
          } else {
            fileList.value.push(file);
            images.value.push({
              id: file.name,
              url: url,
            });
            previewList.value.push(url);
          }
        } else {
          ElNotification.warning({
            title: "Warning",
            message: `图片${file.name}大于2M`,
            offset: 100,
          });
        }
      });
      // emit("publish", fileList.value);
    } else {
      const file = inputFile.files && inputFile.files[0];
      if (file?.size > 2048000) {
        return ElNotification.warning({
          title: "Warning",
          message: "图片不能大于2M",
          offset: 100,
        });
      }
      fileList.value = inputFile?.files || null;
      const windowURL = window.URL || window.webkitURL; // 兼容操作
      toWindowUrl.value = windowURL.createObjectURL(inputFile?.files?.[0]);
      // emit("publish", fileList.value);
      setTimeout(() => {
        inputFile = null;
      }, 200);
    }
  };
  inputFile.click();
};

const removePicture = () => {
  fileList.value = null;
  toWindowUrl.value = "";
};
const selectIcon = (val: string) => {
  const text = val;
  if (currentIndex.value == inputCommentRef.value.innerHTML.length) {
    inputCommentRef.value.innerHTML += text;
  } else {
    // 拼接emoji表情
    let input = inputCommentRef.value.innerHTML;
    let start = input.slice(0, currentIndex.value);
    let end = input.slice(currentIndex.value);
    inputCommentRef.value.innerHTML = start + text + end;
  }
  // 每次拼接完就加一下下标 一个表情的长度是两个字节
  currentIndex.value += 2;
  emit("update:inputText", {
    text: inputCommentRef.value.innerHTML,
    parent: props.parent,
  });
};

const publish = debounce(() => {
  // 发布
  emit("publish", { data: fileList.value, parent: props.parent });
  showPublish.value = false;
}, 500);

// 清空内容
const clear = () => {
  currentIndex.value = getCurrentIndex();
  images.value = [];
  fileList.value = [];
  inputCommentRef.value.innerHTML = "";
  emit("update:inputText", {
    text: inputCommentRef.value.innerHTML,
    parent: props.parent,
  });
};

watch(
  () => props.showPublishButton,
  (newV) => {
    showPublish.value = newV;
  }
);
onMounted(() => {
  if (inputCommentRef.value) {
    inputCommentRef.value.innerHTML = props.inputText;
  }
});

defineExpose({
  clear,
});
</script>

<style lang="scss" scoped>
.input-header {
  height: auto;
  background-color: #c2d5d5;
  .input-inputText {
    background-color: #f2f3f5;
    padding: 12px;
    box-sizing: border-box;
    font-size: 1.2rem;
    font-weight: 700;
    transition: all 0.3s;
    word-break: break-all;
    height: auto;
  }
  .comment-content:empty::before {
    content: attr(placeholder);
    font-size: var(--size);
    // color: #f2f3f5;
    font-weight: 700;
  }
  .comment-picture {
    background-color: #f2f3f5;
    position: relative;
    div {
      width: 28px;
      height: 28px;
      border-radius: 50%;
      position: absolute;
      top: 0;
      left: 35px;
      @include flex();
      span {
        font-size: 1rem;
        color: red;
        font-weight: bold;
      }
    }
    div:hover {
      background-color: #ffffff;
    }
  }
}

.icon-input {
  background-color: #f2f3f5;
  @include flex($space-between);
  height: 2.5rem;
  .icon-select {
    @include flex();
    cursor: pointer;
  }
  .input-picture {
    @include flex();
    font-size: 2rem;
    cursor: pointer;
    width: 50px;
    height: inherit;
  }
}

.clear-btn {
  font-weight: 700;
  border: none;
}

.image-list {
  width: 100%;
  height: auto;
  padding: 5px;
  display: grid;
  grid-template-columns: 10rem 10rem 10rem;
  grid-template-rows: 10rem 10rem 10rem;
  grid-gap: 2px;
  background-color: #f1ebe9;
  .image-container {
    position: relative;
    img {
      width: 100%;
      height: 100%;
    }
    .el-icon {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
}

@media screen and (min-width: 768px) {
  .image-list {
    height: auto;

    grid-template-columns: 10rem 10rem 10rem;
    grid-template-rows: 10rem 10rem 10rem;
    grid-gap: 2px;
  }
  .publish-btn {
    font-size: 1rem;
    height: 1.8rem;
  }
  .clear-btn {
    font-size: 1rem;
    height: 1.8rem;
  }
}

@media screen and (max-width: 768px) {
  .image-list {
    height: 20rem;
    padding: 5px;
    display: grid;
    grid-template-columns: 33% 33% 33%;
    grid-template-rows: 33% 33% 33%;
    grid-gap: 2px;
    background-color: #c2d5d5;
  }
  .publish-btn {
    font-size: 1rem;
    height: 1.5rem;
  }
  .clear-btn {
    font-size: 1rem;
    height: 1.5rem;
  }
}
</style>
